﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Ivony.Html;
using Ivony.Html.Parser;
using WindowsFormsApp1.BLL;
using WindowsFormsApp1.Mode;

namespace WindowsFormsApp1.Tool
{
	public static class  HelpObtain
	{

		static JumonyParser jp = new JumonyParser();

        //获取内页数据
        public static void tiao(string url, Prouduct p, int index)
        {
            try
            {
                for (int i = 0; i < 1000; i += index)
                {
                    if (i > 1)
                    {
                        if (i == 48 && i != 0)
                        {
                            i += 1;
                        }

                        int subUrl = url.LastIndexOf("/");
                        if (url.IndexOf("_Desde") != 0)
                        {
                            string c = url.Substring(0, subUrl);
                            url = "";
                            url = c + "/_Desde_" + i;
                        }
                        else
                        {
                            url += "/_Desde_" + i;
                        }
                    }
                    Debuglog("抓取:" + url+ "_DisplayType_G");
					p.CurrenUrl = url+ "_DisplayType_G";// "https://roupas.mercadolivre.com.br/moda-intima-lingerie/_Desde_49";

					var request = (HttpWebRequest)WebRequest.Create(url);
                    var response = (HttpWebResponse)request.GetResponse();
                    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        htmlStr(responseString, p);
                    }
                }


			}
			catch (Exception E)
			{
				Debuglog(E.Message, p.PUrl);
			}
		}
		/// <summary>
		/// 获取商品列表
		/// </summary>
		/// <param name="str">整个HTML</param>
		/// <param name="p">商品属性</param>
		public static void htmlStr(string str, Prouduct p)
		{
			string c1 = ""; 
			var dataDocument = jp.Parse(str);
			var mumberlist = dataDocument.Find("#searchResults .results-item.article").ToArray();//整体元素
            try
            {
			for (int i = 0; i < mumberlist.Length; i++)
			{   

				 var alink =mumberlist[i].Find("a").ToArray();
				if (alink.Length > 0)
				{
					c1 = alink[0].Attribute("href").Value();//跳转链接  
					p.PUrl = c1;
					if (!string.IsNullOrWhiteSpace(p.PUrl))
					{
						tiaoDetail(c1, p);//跳转到商品详情页
					}
				}
			}


			}
			catch (Exception E)
			{
				Debuglog(E.Message, p.PUrl);
			}
		}

		/// <summary>
		/// 跳转到商品详情页
		/// </summary>
		/// <param name="url"></param>
		/// <param name="p"></param>
		public static void tiaoDetail(string url, Prouduct p)
		{ 
			var request = (HttpWebRequest)WebRequest.Create(url);
			var response = (HttpWebResponse)request.GetResponse();
			var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
			if (!string.IsNullOrWhiteSpace(responseString))
			{
				htmlStrDetail(responseString, p);
			} 
		}

		/// <summary>
		/// 获取商品详情
		/// </summary>
		/// <param name="str">整个HTML</param>
		/// <param name="p">商品属性</param>
		public static void htmlStrDetail(string str, Prouduct p)
		{
			try
			{


				var dataDocument = jp.Parse(str);
				var mumberlist = dataDocument.Find("#gallery_dflt figure").ToArray();//图片 



				//是否自营

				var isZy = dataDocument.Find(".card-title").ToArray();//评分
				string zhi ="0";
				if (isZy.Count() > 0)
				{
					//zhi=isZy[0].Attribute("p").Value().Trim();//获取值 
					if (isZy[0].ToString().IndexOf("loja")>0)
					{
						zhi = "1";
					}
				}
				else {
					zhi = "0";

				}
				p.isZy = int.Parse(zhi);
					string class2 = ""; //1
                string classs = "";//2
                string class3 = "";//3
                var breadcrumb = dataDocument.Find(".vip-navigation-breadcrumb-list li").ToArray();//第三类别
                if (breadcrumb.Length > 0)
                {
                     class2 = breadcrumb[0].InnerText().Trim(); //1
                     classs = breadcrumb[1].InnerText().Trim();//2
                     class3 = breadcrumb[2].InnerText().Trim();//3
                } 
				var OriginalPrice = dataDocument.Find(".price-tag.price-tag__del").ToArray();//原价
				string OriginalPricePrice = "";
				if (OriginalPrice.Length > 0)
				{
					var OriginalPrice1 = OriginalPrice[0].Find(".price-tag-symbol").ToArray();//原价
					OriginalPricePrice = OriginalPrice1[0].Attribute("content").Value();//原价
				}
				else
				{
					OriginalPricePrice = "0";
				}

				var Price = dataDocument.Find(".price-tag").ToArray();//现价
				var Price1 = dataDocument.Find(".price-tag-symbol").ToArray();//现价

				//var OriginalPricePrice = Price1[Price1.Length - 2].Attribute("content").Value();//原价
				var Prices = Price1[Price1.Length - 1].Attribute("content").Value();//现价

				var PComment = dataDocument.Find(".average-legend span").ToArray();//评论数
				string PCommentCount = "";
				if (PComment.Length > 0)
				{

					PCommentCount = PComment[0].InnerText();//评论数
				}
				else
				{
					PCommentCount = "0";
				}

				var SaleCount = dataDocument.Find(".item-conditions").ToArray();//销售总量
				var SaleCounts = SaleCount[0].InnerText();//销售总量 
				if (!string.IsNullOrWhiteSpace(SaleCounts))
				{
					SaleCounts = Regex.Replace(SaleCounts, "\\D+", "");//找出数字 
					int count = Regex.Matches(SaleCounts, @"\d").Count;

					if (count == 0) 
					{
						SaleCounts = "0";
					}
				}
				else {
					SaleCounts = "0";
				}
				var PScore = dataDocument.Find(".review-summary-average").ToArray();//评分
				string PScoreCount = "";
				if (PScore.Length > 0)
				{
					PScoreCount = PScore[0].InnerText();//评分
				}
				else {
					PScoreCount = "0";
				}


			//	var PDescribe = dataDocument.Find(".item-description__content ").ToArray();//描述
			//	string PDescribes = "";
			//	if (PDescribe.Length>0)
			//	{
			//		PDescribes = PDescribe[0].InnerText();//描述
			//	}
			//	else {
					var PDescribes = "";
			//	}
				string PastTimesCounts = "";
				var PastTimesCount = dataDocument.Find(".reputation-relevant strong").ToArray();//过去4个月销售量
				if (PastTimesCount.Length > 0)
				{
					PastTimesCounts = PastTimesCount[0].InnerText();//过去4个月销售量
				}
				else {
					PastTimesCounts = "0";
				}

				var PreferentialProportion = dataDocument.Find(".price-tag.discount-arrow.arrow-left  ").ToArray();//优惠比例
				string PreferentialProportionS = "";
				if (PreferentialProportion.Length > 0)
				{
					PreferentialProportionS = PreferentialProportion[0].InnerText();//优惠比例
					PreferentialProportionS = Regex.Replace(PreferentialProportionS, "\\D+", "");//找出数字  优惠比例
				}
				else {
					PreferentialProportionS = "0";
				}
			

				var pname = dataDocument.Find(".item-title__primary ").ToArray();//商品名称
				var panme1 = pname[0].InnerText();//商品名称

				p.Class1 = class2;//1
				p.Class2 = classs;//2
				p.Class3 = class3;//第三类获取
				p.PName = panme1;//标题
				p.OriginalPrice = decimal.Parse(OriginalPricePrice);//原价
				p.PComment = int.Parse(PCommentCount);//评论条数;
				p.PDescribe = PDescribes;//商品描述
				p.PreferentialProportion = PreferentialProportionS;//优惠比例
				p.Price = decimal.Parse(Prices);//商品价格
				p.PScore = decimal.Parse(PScoreCount);//商品评分
				p.SaleCount = int.Parse(SaleCounts);//销售总量
				p.PastTimesCount = PastTimesCounts;//过去4个月销售量 

				//图片地址获取
				for (int i = 0; i < mumberlist.Length; i++)
				{
					if (i == 7)
					{
						break;
					}
					//获取图片
					var imgUrl = mumberlist[i].Find("a").ToArray();
					if (imgUrl.Length > 0)
					{
						var url = imgUrl[0].Attribute("href").Value();
						if (i == 0)
						{
							p.PicUrl1 = url;
						}
						else if (i == 1)
						{
							p.PicUrl2 = url;
						}
						else if (i == 2)
						{
							p.PicUrl3 = url;
						}
						else if (i == 3)
						{
							p.PicUrl4 = url;
						}
						else if (i == 4)
						{
							p.PicUrl5 = url;
						}
						else if (i == 5)
						{
							p.PicUrl6 = url;
						}
						else if (i == 6)
						{
							p.PicUrl7 = url;
						}
					}
					else
					{
						break;
					}

				}

				if (ProductBLL.Add(p) < 1)
				{
					Debuglog("---------------------没有新增成功-------------"+ p.CategoryClassID+"--"+p.Class1+"--"+ p.Class2 + "--"+ p.Class3 + "--"+p.CategoryClassID + "--");
				}
			}
				catch(Exception E)
			{
				Debuglog(E.Message,p.PUrl);
			}

		}

		private static object LockLog = new object();
		public static void Debuglog(string log, string logname = "_Debuglog.txt",string p="1.txt")
		{
			lock (LockLog)
			{
				try
				{
					System.IO.StreamWriter writer = System.IO.File.AppendText("D:\\log\\" + logname);
					writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + log+",商品地址:"+p);
					writer.WriteLine("---------------");
					writer.Close();
				}
				catch (Exception E)
				{
					Debuglog(E.Message, p);
				}
			}
		}

	}
}
